package com.opages.netty.demo.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author daizhong.liu
 * @create 2021-12-02 18:42
 **/
public class NIOClient {
    public static void main(String[] args) throws IOException {
        //创建客户端
        SocketChannel socketChannel = SocketChannel.open();
        //连接服务端
        boolean connect = socketChannel.connect(new InetSocketAddress("127.0.0.1", 8889));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //检测是否已连接
        if(!connect) {
            //连接是否成功,不成功则等待
            while (!socketChannel.finishConnect()) {
                System.err.println("等待连接服务端!");
            }
        }
        //设置通讯内容
        ByteBuffer byteBuffer = ByteBuffer.wrap("Hello NIO~".getBytes());
        //写向服务端
        socketChannel.write(byteBuffer);
        System.in.read();
    }
}
